// pages/user/userCenter/userCenter.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        inviterConcat: '',
        belongRefer: null,
        showInviter: false,
        showShareImg: false,
        shareImg: [],
        previewImg: '',
        userInfo: null,
        shopInfo: null,
        shopData: null,
        orderInfo: null,
        userCode: '',
        unionID: 1,
        messageInfo: null,
        saveTipsImg: '',
        statusBarHeight: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        //浏览记录
        let data = {
            type: 1,
            client: 2
        }
        common.post('Userbrowse/add_user_browse', data).then(function(res) {}).catch(function(e) {})
        const that = this
        wx.getSystemInfo({
            success(res) {
                that.setData({
                    statusBarHeight: res.statusBarHeight + 5
                })
            }
        })
        this.getUserCode()
        this.getInviterConcat()
        this.getShareImg()
        this.getSaveTipsImg()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.getUserInfo()
        this.getShopInfo()
        this.getShopData()
        this.getOrderInfo()
        this.getMessageInfo()
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.setData({
            inviterConcat: '',
            belongRefer: null,
            showInviter: false,
            showShareImg: false,
            shareImg: [],
            previewImg: '',
            userInfo: null,
            shopInfo: null,
            shopData: null,
            orderInfo: null,
            userCode: '',
            unionID: 1,
            messageInfo: null,
            saveTipsImg: '',
            statusBarHeight: 0
        })
        common.refresh()
        setTimeout(function() {
            wx.stopPullDownRefresh()
        }, 2000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    bindGetUserInfo: function(e) {

    },

    getShareImg: function() {
        let that = this;
        common.post("Upimg/get_app_img", {
            type: 1
        }).then(function(res) {
            that.setData({
                shareImg: res,
                previewImg: res[0]
            })
        }).catch(function(e) {})
    },

    getSaveTipsImg: function() {
        const that = this
        let data = {
            activity: 785,
            images_id: 15
        }
        common.post('Images/get_img', data).then(function(res) {
            that.setData({
                saveTipsImg: res[0].images
            })
        }).catch(function(e) {})
    },

    getShopInfo: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('realStoreId')
        }
        common.post('Store/get_store_info', data).then(function(res) {
            if (res.code == 204) {
                return
            } else {
                that.setData({
                    shopInfo: res
                })
            }
        }).catch(function(e) {})
    },

    getShopData: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('realStoreId')
        }
        common.post('Data/get_today_money', data).then(function(res) {
            if (res.code == 204) {
                return
            } else {
                that.setData({
                    shopData: res
                })
            }
        }).catch(function(e) {})
    },

    getUserInfo: function() {
        const that = this
        let data = {}
        common.post('User/user_info', data).then(function(res) {
            if (res.code == 204) {
                return
            } else {
                that.setData({
                    userInfo: res,
                    unionID: wx.getStorageSync('unionID')
                })
                wx.setStorageSync("roleType", res.role_type)
                wx.setStorageSync("storeId", res.store_id)
                wx.setStorageSync("realStoreId", res.real_store_id)
                wx.setStorageSync("userId", res.user_id)
                wx.setStorageSync("userPhone", res.phone)
                wx.setStorageSync("belongId", res.belong_refer)
                wx.setStorageSync("belongType", res.parent_role_type)
            }
        }).catch(function(e) {})
    },

    getMessageInfo: function() {
        const that = this
        let data = {}
        common.post('System/send', data).then(function(res) {
            if (res.code == 204) {
                return
            }
            that.setData({
                messageInfo: res
            })
        }).catch(function(e) {})
    },

    getOrderInfo: function() {
        const that = this
        let data = {
            client: 2
        }
        common.post('Orderlist/order_num', data).then(function(res) {
            that.setData({
                orderInfo: res
            })
        }).catch(function(e) {})
    },

    getUserCode: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('storeId')
        }
        common.post('QrCodes/app_create_qr', data).then(function(res) {
            that.setData({
                userCode: res
            })
        }).catch(function(e) {})
    },

    getInviterConcat: function() {
        const that = this
        let inviterConcat = this.data.inviterConcat
        let data = {}
        common.post('User/get_user_contact', data).then(function(res) {
            if (res.code == 204) {
                that.setData({
                    inviterConcat: inviterConcat
                })
            } else {
                that.setData({
                    inviterConcat: res
                })
            }
        }).catch(function(e) {})
    },

    closeTips: function() {
        const that = this
        let data = {
            is_collect: 1
        }
        common.post('User/up_info', data).then(function(res) {
            if (res.code == 204) {
                return
            }
            that.data.userInfo.is_collect = 1
            that.setData({
                userInfo: that.data.userInfo
            })
        }).catch(function(e) {})
    },

    showConcat: function() {
        if (this.data.inviterConcat != '您的上级还未上传联系方式' && this.data.inviterConcat != '') {
            wx.hideTabBar()
            this.setData({
                showInviter: true
            })
        } else {
            wx.showToast({
                title: '邀请人暂未上传联系方式',
                icon: 'none',
                duration: 1000
            })
        }
    },

    closeConcat: function() {
        wx.showTabBar()
        this.setData({
            showInviter: false
        })
    },

    invite: function() {
        wx.hideTabBar()
        this.setData({
            showShareImg: true
        })
    },

    closeInvite: function() {
        wx.showTabBar()
        this.setData({
            showShareImg: false
        })
    },

    goSourceIndex: function() {
        wx.navigateTo({
            url: '/pages/source/sourceIndex/sourceIndex'
        })
    },
    exitLogin: function() {
        wx.login({
            success(res) {
                wx.setStorageSync('code', res.code)
            }
        })
        wx.setStorageSync('prePageUrl', '/pages/user/userCenter/userCenter')
        wx.removeStorageSync("token")
        wx.redirectTo({
            url: '/pages/user/login/login',
        })
    },
    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },
    circleImg: function(ctx, img, x, y, r) {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },
    downloadImg: function() {
        wx.showLoading({
            title: '正在生成图片...',
        })
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: 'https:' + that.data.previewImg.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.userInfo.heard_img.split(':')[1]
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.userCode.split(':')[1]
            })
        ]).then(res => {
            const ctx = wx.createCanvasContext('shareCanvas')
            ctx.drawImage(res[0].path, 0, 0, 750, 1234)
            ctx.drawImage(res[2].path, 450, 935, 260, 260)
            this.circleImg(ctx, res[1].path, 40, 40, 50)
            ctx.setFillStyle('#131313')
            ctx.setFontSize(28)
            ctx.fillText(that.data.userInfo.nickname, 160, 73)
            ctx.setFontSize(24)
            ctx.fillText('邀请码：' + that.data.userInfo.user_id, 160, 120)
            ctx.draw(false, function(e) {
                wx.hideLoading()
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                const wxSaveImageToPhotosAlbum = that.promisify(wx.saveImageToPhotosAlbum)
                wxCanvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1234,
                    destWidth: 750,
                    destHeight: 1234
                }, this).then(res => {
                    const saveImg = res.tempFilePath
                    const that = this
                    wx.saveImageToPhotosAlbum({
                        filePath: saveImg,
                        success: function(data) {
                            wx.showToast({
                                title: '保存成功',
                                icon: 'success',
                                duration: 2000
                            })
                        },
                        fail: function(err) {
                            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                                wx.showModal({
                                    title: '用户未授权',
                                    content: '请先开启保存到相册权限，开启后即可保存图片',
                                    success(res) {
                                        if (res.confirm) {
                                            wx.openSetting({
                                                success(settingdata) {
                                                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                        wx.saveImageToPhotosAlbum({
                                                            filePath: saveImg,
                                                            success(res) {
                                                                wx.showToast({
                                                                    title: '保存成功',
                                                                    icon: 'success',
                                                                    duration: 2000
                                                                })
                                                            }
                                                        })
                                                    } else {
                                                        wx.showToast({
                                                            title: '保存图片失败，请确认开启授权后重新保存图片',
                                                            icon: 'none',
                                                            duration: 2000
                                                        })
                                                    }
                                                }
                                            })
                                        } else if (res.cancel) {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                })
            })
        })
    },
    preview(e) {
        this.setData({
            previewImg: e.target.dataset.img
        })
    }
})